import store from '@/store';
import config from '@/config';
import storage from '@/utils/storage';
import { removeToken } from '@/utils/auth';
import {
  getAccessToken,
  getRefreshToken,
  getTenantId,
  getCurRoute
} from '@/utils/auth';
import { refreshTokenNew } from '@/api/system/user';
import errorCode from '@/utils/errorCode';
import { toast, showConfirm, tansParams } from '@/utils/common';

let timeout = 10000;
const baseUrl = config.baseUrl + config.baseApi;
const loginUrl = config.loginUrl + config.baseApi;
const whiteList = [
  '/system/tenant/get-id-by-username',
  '/system/auth/refresh-token',
  ''
];
export const request = (config) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getAccessToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getAccessToken();
  }
  // 设置租户
  config.header['tenant-id'] = getTenantId();
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  if (whiteList.includes(config.url)) {
    config.header = {};
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      })
      .then((response) => {
        if (!response.length) {
          return;
        }
        const res = response[1];
        const code = res.data.code;
        const msg = errorCode[code] || res.data.msg || errorCode['default'];
        const refreshTok = getRefreshToken();
        if (code == 0) {
          resolve(res.data);
        } else if (
          code == 400 &&
          config.url.indexOf('/system/auth/refresh-token') != -1
        ) {
          clearStorage();
          uni.reLaunch({
            url: '/packageA/pages/login'
          });
          reject('无效的会话，或者会话已过期，请重新登录。');
        } else if (code == 401) {
          if (!getRefreshToken()) {
            // refreshtoken过期后才提示用户去登录
            showConfirm(
              '登录状态已过期，您可以继续留在该页面，或者重新登录?'
            ).then((res) => {
              clearStorage();
              if (res.confirm) {
                uni.reLaunch({
                  url: '/packageA/pages/login'
                });
              }
            });
            reject('无效的会话，或者会话已过期，请重新登录。');
          } else {
            //保存路由
            if (config.url.indexOf('/system/auth/refresh-token') == -1) {
              let routes = getCurrentPages();
              let curRoute = routes[routes.length - 1].route;
              uni.setStorageSync('CUR_ROUTE', curRoute);
            }
            refreshTokenNew(refreshTok).then((res) => {
              if (res.code == 0) {
                uni.setStorageSync('ACCESS_TOKEN', res.data.accessToken);
                uni.setStorageSync('REFRESH_TOKEN', res.data.refreshToken);
                if (res.code == 0) {
                  uni.reLaunch({
                    url: '/' + getCurRoute()
                  });
                  return;
                }
              } else {
                //换令牌失败后只能提示用户去登录
                showConfirm(
                  '登录状态已过期，您可以继续留在该页面，或者重新登录?'
                ).then((res) => {
                  if (res.confirm) {
                    clearStorage();
                    uni.reLaunch({
                      url: '/packageA/pages/login'
                    });
                  }
                });
                reject('无效的会话，或者会话已过期，请重新登录。');
              }
            });
          }
        } else if (code == 403) {
          clearStorage();
          uni.reLaunch({
            url: '/packageA/pages/login'
          });
        } else if (code == 1002015002) {
          uni.reLaunch({
            url: '/packageA/pages/error?mess=' + msg
          });
          toast(msg);
          reject(msg);
        } else {
          resolve(res.data);
        }
      })
      .catch((error) => {
        let { message } = error;
        if (message === 'Network Error') {
          message = '网络连接异常';
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常';
        }
        toast(message);
        reject(error);
      });
  });
};

export const requestLg = (config) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getAccessToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getAccessToken();
  }
  // 设置租户
  config.header['tenant-id'] = getTenantId();
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  if (whiteList.includes(config.url)) {
    config.header = {};
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: config.loginUrl || loginUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      })
      .then((response) => {
        if (!response.length) {
          return;
        }
        const res = response[1];
        const code = res.data.code;
        const msg = errorCode[code] || res.data.msg || errorCode['default'];
        const refreshTok = getRefreshToken();
        if (code == 0) {
          resolve(res.data);
        } else if (
          code == 400 &&
          config.url.indexOf('/system/auth/refresh-token') != -1
        ) {
          clearStorage();
          uni.reLaunch({
            url: '/packageA/pages/login'
          });
          reject('无效的会话，或者会话已过期，请重新登录。');
        } else if (code == 401) {
          if (!getRefreshToken()) {
            // refreshtoken过期后才提示用户去登录
            showConfirm(
              '登录状态已过期，您可以继续留在该页面，或者重新登录?'
            ).then((res) => {
              if (res.confirm) {
                clearStorage();
                uni.reLaunch({
                  url: '/packageA/pages/login'
                });
              }
            });
            reject('无效的会话，或者会话已过期，请重新登录。');
          } else {
            //保存路由
            if (config.url.indexOf('/system/auth/refresh-token') == -1) {
              let routes = getCurrentPages();
              let curRoute = routes[routes.length - 1].route;
              uni.setStorageSync('CUR_ROUTE', curRoute);
            }
            refreshTokenNew(refreshTok).then((res) => {
              if (res.code == 0) {
                uni.setStorageSync('ACCESS_TOKEN', res.data.accessToken);
                uni.setStorageSync('REFRESH_TOKEN', res.data.refreshToken);
                if (res.code == 0) {
                  uni.reLaunch({
                    url: '/' + getCurRoute()
                  });
                  return;
                }
              } else {
                //换令牌失败后只能提示用户去登录
                showConfirm(
                  '登录状态已过期，您可以继续留在该页面，或者重新登录?'
                ).then((res) => {
                  if (res.confirm) {
                    clearStorage();
                    uni.reLaunch({
                      url: '/packageA/pages/login'
                    });
                  }
                });
                reject('无效的会话，或者会话已过期，请重新登录。');
              }
            });
          }
        } else if (code == 403) {
          clearStorage();
          uni.reLaunch({
            url: '/packageA/pages/login'
          });
        } else if (code == 1002015002) {
          uni.reLaunch({
            url: '/packageA/pages/error?mess=' + msg
          });
          toast(msg);
          reject(msg);
        } else {
          resolve(res.data);
        }
      })
      .catch((error) => {
        let { message } = error;
        if (message === 'Network Error') {
          message = '网络连接异常';
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常';
        }
        toast(message);
        reject(error);
      });
  });
};

const clearStorage = () => {
  storage.set('vuex_roles', []);
  storage.set('vuex_permissions', []);
  storage.clean();
  removeToken();
};
